<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from '../plugins/axios'

const router = useRouter()

const props = defineProps({
  announcements: {
    type: Array,
    required: true,
    default: () => []
  },
  showActions: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['viewDetail', 'viewMore', 'edit', 'delete'])

const handleViewDetail = (announcement) => {
  router.push(`/announcement/${announcement.id}`)
}

const handleViewMore = (site) => {
  router.push({
    path: '/announcement/list',
    query: {
      site: site
    }
  })
}

const handleEdit = (announcement) => {
  emit('edit', announcement)
}

const handleDelete = async (announcement) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条公告吗？此操作不可恢复',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await axios.delete(`/public/${announcement.id}`)
    
    if (response.data.code === 1) {
      ElMessage.success('删除成功')
      emit('delete', announcement)  // 通知父组件删除成功
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 默认头像URL
const defaultAvatar = '/default-avatar.png'

// 格式化时间的计算属性
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const isAdmin = localStorage.getItem('isAdmin') === '1'
const userId = Number(localStorage.getItem('userId'))
</script>

<template>
  <div class="announcement-list">
    <div v-for="announcement in announcements" :key="announcement.id" class="announcement-item">
      <div class="announcement-header">
        <h3 class="title" @click="handleViewDetail(announcement)">{{ announcement.title }}</h3>
        <div class="actions" v-if="showActions && (isAdmin || userId === announcement.userId)">
          <button @click="handleEdit(announcement)" class="action-btn edit">修改</button>
          <button @click="handleDelete(announcement)" class="action-btn delete">删除</button>
        </div>
      </div>
      <div class="announcement-info">
        <div class="author-info">
          <img 
            :src="announcement.user.head || defaultAvatar" 
            :alt="announcement.author"
            class="author-avatar"
          />
          <span>Author: {{ announcement.user.realname }}</span>
           <!-- 使用计算属性格式化时间 -->
          <span>PublishTime: {{ formatTime(announcement.publishTime) }}</span>
          <span>Site: {{ announcement.site.siteName }}</span>
        </div>
       
      </div>
    </div>
  </div>
</template>

<style scoped>
.announcement-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.announcement-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.title {
  margin: 0;
  font-size: 1.1rem;
  color: #333;
  cursor: pointer;
}

.title:hover {
  color: #0052cc;
}

.actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  padding: 0.25rem 0.75rem;
  border-radius: 3px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
  background-color: white;
}

.action-btn.edit {
  color: #67C23A;
  border: 1px solid #67C23A;
}

.action-btn.edit:hover {
  background-color: #f0f9eb;
  border-color: #67C23A;
  color: #67C23A;
}

.action-btn.delete {
  color: #F56C6C;
  border: 1px solid #F56C6C;
}

.action-btn.delete:hover {
  background-color: #fef0f0;
  border-color: #F56C6C;
  color: #F56C6C;
}

.announcement-info {
  display: flex;
  gap: 1rem;
  color: #666;
  font-size: 0.9rem;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.author-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
}
</style>